#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <functional>

using namespace muduo;
using namespace muduo::net;

// 简洁封装，接口只保留「连接/收发/退出」
class DictClient {
public:
    DictClient(EventLoop* loop, const InetAddress& serverAddr)
        : client_(loop, serverAddr, "DictClient") {
        client_.setConnectionCallback(
            std::bind(&DictClient::onConnection, this, _1));
        client_.setMessageCallback(
            std::bind(&DictClient::onMessage, this, _1, _2, _3));
    }

    void connect() { client_.connect(); }
    void disconnect() { client_.disconnect(); }
    bool connected() const { return conn_ && conn_->connected(); }

    // 阻塞读一行并发送，直到 EOF
    void run() {
        std::string line;
        while (std::getline(std::cin, line)) {
            if (!connected()) break;
            line += "\n";
            conn_->send(line);
        }
        disconnect();
    }

private:
    void onConnection(const TcpConnectionPtr& conn) {
        if (conn->connected()) {
            conn_ = conn;
            std::cout << "Connected, input word to translate:\n> " << std::flush;
        } else {
            conn_.reset();
            std::cout << "Disconnected.\n";
        }
    }

    void onMessage(const TcpConnectionPtr&, Buffer* buf, Timestamp) {
        std::string rsp = buf->retrieveAllAsString();
        std::cout << rsp << "> " << std::flush;
    }

    TcpClient client_;
    TcpConnectionPtr conn_;
};

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cerr << "Usage: ./client <host> <port>\n";
        return 1;
    }

    EventLoop loop;
    InetAddress serverAddr(argv[1], static_cast<uint16_t>(std::stoi(argv[2])));
    DictClient client(&loop, serverAddr);

    client.connect();
    loop.runAfter(0.0, [&client] { client.run(); });
    loop.loop();
    return 0;
}